#include "main.h"

#include "wirish.h"
#include <HardwareSPI.h>

#include "SdFat.h"
#include "SoftI2C.h"

#include "MMA7455.h"
#include "EB570.h"
#include "WISMO228.h"

HardwareSPI spi1(1);// Used for microSD card and RFM70
Sd2Card		card;
SoftI2C		i2c;	// Used for accelerometer chip

MMA7455		acc;
WISMO228	gsm;
EB570		gps;

/*
 *	SysTick timer handler
*/
volatile uint16 systick_downtimer;
volatile uint16 systick_key_timer;

void user_SysTickHandler(void)
{
	if (systick_downtimer != 0)
		--systick_downtimer;
/*
	if (KEY_PRESS())
	{
		if (systick_key_timer == 0)
			systick_key_timer = KEY_DEBOUNCE_RESET;
		else if(--systick_key_timer == 0)
			SystemRestart();
	}
	else
		systick_key_timer = 0;
*/
}

void setup()
{
	// Serial Wire debug only
	afio_cfg_debug_ports(AFIO_DEBUG_SW_ONLY);

	// Initialize ports
	// ...

	// Attach to system tick timer (see above)
	systick_key_timer = 0;
	systick_downtimer = 0;
	systick_set_callback(user_SysTickHandler);


	i2c.begin(ACC_SDA, ACC_SCL);
	acc.begin(&i2c);

	gps.power(GPS_POWER, 0);
	gsm.power(GSM_POWER, 0);

	gsm.begin(&Serial1, 115200);
	gps.begin(&Serial2, 9600);

	spi1.begin(SPI_281_250KHZ, MSBFIRST, 0);
	if (!card.init(&spi1))
		SerialUSB.println("card.init failed");
	else
	{
		SerialUSB.println("card.init passed");
		spi1.end();

		spi1.begin(SPI_4_5MHZ, MSBFIRST, 0);
		delay(100);
	}
}

void loop()
{

}

// Force init to be called *first*, i.e. before static object allocation.
// Otherwise, statically allocated objects that need libmaple may fail.
__attribute__((constructor)) void premain()
{
	init();
}

int main(void)
{
	setup();
	while (true)
	{
		loop();
	}
	return 0;
}
